package com.ruoyi.system.service.impl;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.io.File;
import java.io.IOException;


import com.baidu.aip.ocr.AipOcr;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;

import com.ruoyi.file.utils.FileUploadUtils;
import com.ruoyi.system.service.IdCardInfoService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.system.domain.IdCardInfo;
import com.ruoyi.system.mapper.IdCardInfoMapper;
import com.ruoyi.system.service.IdCardInfoService;



import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 身份证识别信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-26
 */
@Service
public class IdCardInfoServiceImpl extends ServiceImpl<IdCardInfoMapper, IdCardInfo> implements IdCardInfoService
{
    @Autowired
    private IdCardInfoMapper idCardInfoMapper;

    // 百度AI配置
    @Value("${baidu.ai.appId}")
    private String appId;

    @Value("${baidu.ai.apiKey}")
    private String apiKey;

    @Value("${baidu.ai.secretKey}")
    private String secretKey;

    // 上传路径
    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * 查询身份证识别信息
     *
     * @param id 身份证识别信息主键
     * @return 身份证识别信息
     */
    @Override
    public IdCardInfo selectIdCardInfoById(Long id)
    {
        return idCardInfoMapper.selectIdCardInfoById(id);
    }

    /**
     * 查询身份证识别信息列表
     *
     * @param idCardInfo 身份证识别信息
     * @return 身份证识别信息
     */
    @Override
    public List<IdCardInfo> selectIdCardInfoList(IdCardInfo idCardInfo)
    {
        return idCardInfoMapper.selectIdCardInfoList(idCardInfo);
    }

    /**
     * 新增身份证识别信息
     *
     * @param idCardInfo 身份证识别信息
     * @return 结果
     */
    @Override
    public int insertIdCardInfo(IdCardInfo idCardInfo)
    {
        idCardInfo.setCreateTime(DateUtils.getNowDate());
        idCardInfo.setCreateBy(SecurityUtils.getUsername());
        return idCardInfoMapper.insertIdCardInfo(idCardInfo);
    }

    /**
     * 修改身份证识别信息
     *
     * @param idCardInfo 身份证识别信息
     * @return 结果
     */
    @Override
    public int updateIdCardInfo(IdCardInfo idCardInfo)
    {
        idCardInfo.setUpdateTime(DateUtils.getNowDate());
        idCardInfo.setUpdateBy(SecurityUtils.getUsername());
        return idCardInfoMapper.updateIdCardInfo(idCardInfo);
    }

    /**
     * 批量删除身份证识别信息
     *
     * @param ids 需要删除的身份证识别信息主键
     * @return 结果
     */
    @Override
    public int deleteIdCardInfoByIds(Long[] ids)
    {
        return idCardInfoMapper.deleteIdCardInfoByIds(ids);
    }

    /**
     * 删除身份证识别信息信息
     *
     * @param id 身份证识别信息主键
     * @return 结果
     */
    @Override
    public int deleteIdCardInfoById(Long id)
    {
        return idCardInfoMapper.deleteIdCardInfoById(id);
    }

    /**
     * 上传并识别身份证
     */
    @Override
    public IdCardInfo uploadAndRecognizeIdCard(MultipartFile file) throws Exception {
        // 1. 上传文件
        String fileName = FileUploadUtils.upload(profile + "/idcard", file);
        String imageUrl = fileName.replace(profile, "");
        String localFilePath = profile + imageUrl;

        // 2. 调用百度AI OCR接口识别身份证
        AipOcr client = new AipOcr(appId, apiKey, secretKey);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 调用身份证识别接口
//        JSONObject res = JSONObject.from(client.idcard(localFilePath, "front", null));原来的
        JSONObject res = new JSONObject(client.idcard(localFilePath, "front", null));


        // 3. 解析识别结果
        IdCardInfo idCardInfo = new IdCardInfo();
        if (res.has("words_result")) {
            JSONObject wordsResult = res.getJSONObject("words_result");

            idCardInfo.setName(wordsResult.getJSONObject("姓名").getString("words"));
            idCardInfo.setGender(wordsResult.getJSONObject("性别").getString("words"));
            idCardInfo.setNation(wordsResult.getJSONObject("民族").getString("words"));

            String birthStr = wordsResult.getJSONObject("出生").getString("words");
            try {
                idCardInfo.setBirth(new SimpleDateFormat("yyyyMMdd").parse(birthStr));
            } catch (ParseException e) {
                // 处理日期格式异常
                idCardInfo.setBirth(null);
            }

            idCardInfo.setAddress(wordsResult.getJSONObject("住址").getString("words"));
            idCardInfo.setIdCardNumber(wordsResult.getJSONObject("公民身份号码").getString("words"));
        }

        // 4. 设置其他信息
        idCardInfo.setImageUrl(imageUrl);
        idCardInfo.setRecognitionTime(new Date());
        idCardInfo.setCreateBy(SecurityUtils.getUsername());
        idCardInfo.setCreateTime(new Date());

        // 5. 保存到数据库
        idCardInfoMapper.insertIdCardInfo(idCardInfo);

        return idCardInfo;
    }

}